import { defineStore } from 'pinia'
import request from '../utils/request'

export const useAuthStore = defineStore('auth', {
  state: () => {
    const user = JSON.parse(localStorage.getItem('user')) || null
    const token = localStorage.getItem('token') || ''
    return {
      user,
      token,
      isLoggedIn: !!user
    }
  },

  actions: {
    async login(phone, password) {
      try {
        const result = await request.post('/auth/login', { phone, password })
        console.log(result)
        if (result.code === 200) {
          this.isLoggedIn = true
          this.user = result.data.user
          this.token = result.data.token
          localStorage.setItem('user', JSON.stringify(result.data.user))
          localStorage.setItem('token', result.data.token)
          return true
        }
        return false
      } catch (error) {
        console.error('登录失败:', error)
        return false
      }
    },

    async register(phone, name, password) {
      try {
        const result = await request.post('/auth/register', { phone, name, password })
        if (result.code === 200) {
          this.isLoggedIn = true
          this.user = result.data.user
          this.token = result.data.token
          localStorage.setItem('user', JSON.stringify(result.data.user))
          localStorage.setItem('token', result.data.token)
          return true
        }
        return false
      } catch (error) {
        console.error('注册失败:', error)
        return false
      }
    },

    async logout() {
      try {
        await request.post('/auth/logout')
      } catch (error) {
        console.error('退出登录失败:', error)
      } finally {
        this.isLoggedIn = false
        this.user = null
        this.token = ''
        localStorage.removeItem('user')
        localStorage.removeItem('token')
      }
    },

    async refreshUserInfo() {
      if (!this.token) {
        this.isLoggedIn = false
        return false
      }

      try {
        const result = await request.get('/users/me')
        if (result.code === 200) {
          this.isLoggedIn = true
          this.user = result.data
          localStorage.setItem('user', JSON.stringify(result.data))
          return true
        } else {
          this.clearAuth()
          return false
        }
      } catch (error) {
        console.error('验证登录状态失败:', error)
        this.clearAuth()
        return false
      }
    },

    clearAuth() {
      this.isLoggedIn = false
      this.user = null
      this.token = ''
      localStorage.removeItem('user')
      localStorage.removeItem('token')
    }
  }
})
